#include <iostream>
#include <string>
#include <unistd.h>
// #include <pthread.h>
#include "thread.hpp"
#include <memory.h>
#include <memory>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

using namespace std;
// int sock = -1;

uint16_t server_port = 0;
string server_ip;

static void usage(std::string porc)
{
    std::cout << "\nUsage: " << porc << " server_ip  server_port\n"
              << std::endl;
}

static void *upd_send(void *args)
{
    int sock = *(int *)(((ThreadData *)args)->_args);
    string name = ((ThreadData *)args)->_name;

    string message;
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());

    while (true)
    {
        cerr << "输入用户信息：";
        getline(cin, message);
        if (message == "quit")
            break;

        // 当client首次向服务器发消息时，os会自动给client bind它的IP和port
        sendto(sock, message.c_str(), message.size(), 0,
               (struct sockaddr *)&server, sizeof(server));
    }

    return nullptr;
}

static void *upd_recv(void *args)
{
    int sock = *(int *)(((ThreadData *)args)->_args);
    string name = ((ThreadData *)args)->_name;

    char buff[1024];
    while (true)
    {
        memset(buff, 0, sizeof(buff));
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        ssize_t s = recvfrom(sock, buff, sizeof(buff), 0,
                             (struct sockaddr *)&temp, &len);

        if (s > 0)
        {
            buff[s] = 0; // 成功
            cout << buff << endl;
        }
    }
    return nullptr;
}

//./udp_server 127.0.0.1  8080
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        usage(argv[0]);
        exit(1);
    }

    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        printf("socket创建失败\n");
        exit(2);
    }
    server_port = atoi(argv[2]);
    server_ip = argv[1];

    // client需要绑定吗? --需要，但一般不会显示绑定，程序员不会自己bind
    // 因为client是其他人下载使用的，如果程序员bind了
    // 当其他进程先占领了这个IP和port，绑定失败，客户端启动失败
    // 所以client不会显示bind指定port，要os自动选择（什么时候）

    unique_ptr<Thread> sender(new Thread(1, upd_send, (void *)&sock));
    unique_ptr<Thread> recver(new Thread(1, upd_recv, (void *)&sock));

    sender->start();
    recver->start();

    sender->join();
    recver->join();

    // string message;
    // struct sockaddr_in server;
    // memset(&server, 0, sizeof(server));
    // server.sin_family = AF_INET;
    // server.sin_port = htons(atoi(argv[2]));
    // server.sin_addr.s_addr = inet_addr(argv[1]);

    // char buff[1024];
    // while (true)
    // {
    //     cout << "输入用户信息：";
    //     getline(cin, message);
    //     if (message == "quit")
    //         break;
    //
    //     // 当client首次向服务器发消息时，os会自动给client bind它的IP和port
    //     sendto(sock, message.c_str(), message.size(), 0,
    //            (struct sockaddr *)&server, sizeof(server));
    //
    //     struct sockaddr_in temp;
    //     socklen_t len = sizeof(temp);
    //     ssize_t s = recvfrom(sock, buff, sizeof(buff), 0,
    //                          (struct sockaddr *)&temp, &len);
    //
    //     if (s > 0)
    //     {
    //         // 成功
    //         buff[s] = 0;
    //         cout << "server echo: " << buff << endl;
    //     }
    // }
    close(sock);

    return 0;
}